|
|
|
|
|
|
|
following code, you don't need to declare the variable before using it unless the Option Explicit statement is used: |
|
|
|
|
|
|
|
|
Private Sub cmdCalcAmt_Click()
TempAmt = Csng(txtAmt_Total.Text)
TempAmt = TempAmt * 1.06
MsgBox This is the final total: & TempAmt
End Sub |
|
|
|
|
|
|
|
|
However, Visual Basic will automatically create a variable that you can use, just as if you declared it yourself. Although this is convenient, it can lead to error in your code if you misspell a variable. To see how easily this could happen, try this on your computer. Start a new project and add a command button and text box to the default form. Then add the preceding code to the form. Now run the application, enter a number in the text box, and click the command button. You should see a message box with a valid number being displayed. Now, to see what would happen if you misspelled the variable somewhere in the code, change the second line to the following: |
|
|
|
|
|
|
|
|
Now, run the application again. This time, you should not see any number when the message box is displayed. Because the TempAmt variable was misspelled on the next-to-last line of the code, this function will always display a zero on the message box. Whenever Visual Basic encounters a new variable name, it doesn't know whether you meant to declare a new variable or you just misspelled an existing one, so it creates a new variable for you. To avoid this problem, you can tell Visual Basic to warn you whenever it encounters a name that was not explicitly declared as a variable. |
|
|
|
|
|
|
|
|
When you place the Option Explicit statement in the Declarations section of any module in your application, it will prevent you from having this problem. |
|
|
|
|
|
|
|
|
Tip You can automatically insert the Option Explicit statement in any new modules that you add to the application by choosing Tools, Options from the Visual Basic menu; then click the Editor tab and check the Require Variable Declaration option. |
|
|
|
|
|
|
|
|
|
|
Caution If you already have some modules in your application, you must manually add the Option Explicit statement to each of them. |
|
|
|
|
|
|
|